package FWK.util;

import java.beans.PropertyVetoException;
import java.util.Map;

import javax.swing.JFrame;

import FWK.core.FwkContext;
import FWK.core.FwkController;
import FWK.core.FwkErrorMannager;
import FWK.core.FwkInternalView;

public class FwkViewFactory {

	/**
	 * Crea las instancias de las ventanas de la aplicacion asignandole el
	 * controller especifico de acuerdo a su clase o a su ventana
	 * 
	 * @param parent
	 *            frame del cual va a depender {@link JFrame}
	 * @param viewClass
	 *            <T extends FwkView> la ventana a instanciar
	 * @param request
	 *            {link Map} simula el request web, utilizado tambien para tomar
	 *            decisiones de subtipos de controllers a una ventana, la
	 *            ventana se entera en el metodo {@code
	 *            FwkView.initialize(request)}
	 * @return {@link FwkInternalView}
	 * */
	public static <T extends FwkInternalView> T showInternalWindow(Class<T> viewClass, FwkInternalView viewAnt,
			JFrame parent, Map<String, ? extends Object> request) {

		T viewInstance = null;
		try {
			FwkContext context = FwkContext.getInstance();
			viewInstance = context.getBean(viewClass);
			FwkController c = viewInstance.getController();
			c.setView(viewInstance, parent);
			c.serViewAnt(viewAnt);
		} catch (Exception e) {
			System.err.println(e);
			FwkErrorMannager.error(e, "Error al abrir la ventana", viewInstance);
		}
		viewInstance.initialize(request);
		parent.getContentPane().add(viewInstance);
		viewInstance.setLocation(viewInstance.getParent().getWidth() / 2 - viewInstance.getWidth() / 2, viewInstance
				.getParent().getHeight()
				/ 2 - viewInstance.getHeight() / 2 - 20);
		try {
			viewInstance.setSelected(true);
		} catch (PropertyVetoException e) {
		}
		return viewInstance;
	}
}
